<template>
  <div>
    <el-page-header @back="$router.back()">
      <template #content>
        <span style="font-size:18px; font-weight:600;">{{ detail.productName }} {{ detail.productCode }}</span>
      </template>
      <template #extra>
        <el-button @click="$router.push({ path: 'CreateProdut', query: { productId: detail.productId } })">
          编辑
        </el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
        <el-button :type="detail.productState === 1 ? 'warning' : 'success'" @click="handleToggleStatus">
          {{ detail.productState === 1 ? '停用' : '启用' }}
        </el-button>
        <el-button @click="openPrintDialog">打印</el-button>
       
      </template>
    </el-page-header>

    <!-- 第一个卡片：货品详情信息 -->
    <el-card style="margin-top:12px;">
      <div style="display:flex; gap:24px;">
        <!-- 左侧轮播图区域 -->
        <div style="width:300px; flex-shrink:0;">
          <!-- 转播图 -->
          <el-carousel v-if="imageList.length > 0" :interval="2000" height="300px" arrow="always"
            indicator-position="outside" style="border-radius:8px; overflow:hidden;">
            <el-carousel-item v-for="(img, index) in imageList" :key="index">
              <el-image :src="img.url" fit="contain" style="width:100%; height:300px; cursor:pointer;"
                :preview-src-list="imageList.map(i => i.url)" :initial-index="index" />
            </el-carousel-item>
          </el-carousel>
          <!-- 无图片占位符 -->
          <div v-else
            style="width:300px; height:300px; background:#f5f7fa; display:flex; align-items:center; justify-content:center; border-radius:8px;">
            <el-icon size="48" color="#ccc">
              <Picture />
            </el-icon>
          </div>

          <!-- 库存统计信息 -->
          <div style="margin-top:16px; text-align:center;">
            <div style="font-size:22px; font-weight:600; color:#333; margin-bottom:12px;">
              {{ detail.inventoryCurrtnumber }}
            </div>
            <div style="font-size:14px; color:#666; margin-bottom:4px;">总库存</div>
            <div style="font-size:22px; font-weight:600; color:#333; margin-bottom:12px;">{{ detail.inventoryMoney }}
            </div>
            <div style="font-size:14px; color:#666; margin-bottom:4px;">库存总金额</div>
          </div>
        </div>

        <!-- 右侧详情信息区域 -->
        <div style="flex:1;">
          <!-- 价格高亮信息 -->
          <div
            style="background:#f0f9ff; border:1px solid #91d5ff; padding:14px 18px; border-radius:6px; display:flex; gap:40px; align-items:center; margin-bottom:16px;">
            <div>
              <span style="color:#666; font-size:14px;">入库参考价：</span>
              <span style="color:#ff4d4f; font-size:22px; font-weight:600; margin-left:4px;">{{
                detail.productInmoney?.toFixed?.(2) || '100.00' }}</span>
            </div>
            <div>
              <span style="color:#666; font-size:14px;">出库参考价：</span>
              <span style="color:#ff4d4f; font-size:22px; font-weight:600; margin-left:4px;">{{
                detail.productOutmoney?.toFixed?.(2) || '200.00' }}</span>
            </div>
          </div>

          <!-- 货品详细信息表 -->
          <el-descriptions :column="3" border size="small" style="margin-bottom:12px;">
            <el-descriptions-item label="货品类型">{{ detail.producttypeName }}</el-descriptions-item>
            <el-descriptions-item label="规格型号">{{ detail.productUnit }}</el-descriptions-item>
            <el-descriptions-item label="单位/条码">
              <el-tag size="small"> {{ detail.unitName }} ({{ detail.productBarcode }} )</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="供应商">{{ detail.supplierName }}</el-descriptions-item>
            <el-descriptions-item label="客户名称">{{ detail.customerName }}</el-descriptions-item>
            <el-descriptions-item label="保质期管理">
              <el-tag size="small" :type="detail.productShelf === 1 ? 'success' : 'info'">
                {{ detail.productShelf === 1 ? '开启' : '关闭' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="保质期">{{ detail.productShelfday }}</el-descriptions-item>
            <el-descriptions-item label="预警天数">{{ detail.productWarningDay }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag size="small" :type="detail.productState === 1 ? 'success' : 'danger'">
                {{ detail.productState === 1 ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="排序" :span="3">{{ detail.productOrderby }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="3">{{ detail.productNote || '无' }}</el-descriptions-item>
          </el-descriptions>

          <!-- 审计信息 -->
          <el-descriptions :column="4" border size="small">
            <el-descriptions-item label="创建人">{{ detail.createor }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatTime(detail.createrTime) }}</el-descriptions-item>
            <el-descriptions-item label="更新人">{{ detail.updater }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatTime(detail.updateTime) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 第二个卡片：标签页展示详细信息 -->
    <el-card style="margin-top:12px; margin-bottom:20px;">
      <el-tabs v-model="activeTab" type="card">
        <!-- 其他信息标签页 -->
        <el-tab-pane label="其他信息" name="other">
          <div style="padding:20px;">
            <h4 style="margin-bottom:16px; font-size:16px; color:#333;">附件</h4>
            <div v-if="fileList.length > 0">
              <div v-for="file in fileList" :key="file.mediaId" style="margin-bottom:10px;">
                <el-link :href="file.url" target="_blank" type="success" :underline="false">
                  <el-icon style="margin-right:4px;">
                    <Document />
                  </el-icon>
                  {{ file.name }}
                </el-link>
              </div>
            </div>
            <el-empty v-else description="暂无附件" :image-size="100" />
          </div>
        </el-tab-pane>

        
      </el-tabs>
    </el-card>

    <!-- 打印弹框 -->
    <el-dialog v-model="showPrintDialog" title="打印" width="600px">
      <div id="printContent" class="print-content">
        <div class="print-header">
          <div class="qr-code-section">
            <canvas ref="qrCodeCanvas" width="120" height="120"></canvas>
            <div class="product-code">{{ detail.productCode || detail.ProductCode }}</div>
          </div>
          <div class="product-info-table">
            <table class="info-table">
              <tr>
                <td class="label">货品名称</td>
                <td class="value">{{ detail.productName || detail.ProductName }}</td>
              </tr>
              <tr>
                <td class="label">货品类型</td>
                <td class="value">{{ detail.producttypeName || detail.ProducttypeName || detail.productTypeName }}</td>
              </tr>
              <tr>
                <td class="label">规格型号</td>
                <td class="value">{{ detail.productspecification }}</td>
              </tr>
              <tr>
                <td class="label">所在仓库</td>
                <td class="value">仓库一/库位二</td>
              </tr>
            </table>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showPrintDialog = false">取消</el-button>
        <el-button type="primary" @click="handlePrint">打印</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import myaxios from '@/http/MyAxios'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as QRCode from 'qrcode'
import { Picture, Document, ArrowDown, Printer } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const detail = reactive<any>({})
const activeTab = ref('other')
const imageList = ref<any[]>([])
const fileList = ref<any[]>([])
const showPrintDialog = ref(false)
const qrCodeCanvas = ref<HTMLCanvasElement>()

// 入库记录相关数据
const inboundRecords = ref<any[]>([])
const inboundLoading = ref(false)
const inboundFilter = reactive({
  warehousingCode: '',
  warehousingTypeId: null as number | null,
  warehouseId: null as number | null
})
const inboundPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})
const inboundTypeList = ref<any[]>([])
const warehouseList = ref<any[]>([])

const formatTime = (v: any) => {
  if (!v) return ''
  const d = new Date(v)
  if (isNaN(d.getTime())) return String(v)
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

const formatDate = (v: any) => {
  if (!v) return ''
  const d = new Date(v)
  if (isNaN(d.getTime())) return String(v)
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
}

const loadDetail = () => {
  // 优先使用productId，如果没有则使用productCode
  const productId = route.query.productId
  const productCode = route.query.productCode

  if (productId) {
    // 使用productId获取详情
    myaxios({ url: '/api/Product/GetProductById', method: 'get', params: { productId: productId } })
      .then(res => {
        if (res.data.code === 200) {
          Object.assign(detail, res.data.data || {})
          console.log('通过productId获取的详情数据:', res.data.data)
          // 加载图片和附件
          if (detail.productId || detail.ProductId) {
            loadMedia(detail.productId || detail.ProductId)
          }
        } else {
          ElMessage.error(res.data.message || '加载失败')
        }
      })
      .catch(() => ElMessage.error('加载失败'))
  } else if (productCode) {
    // 使用productCode获取详情
    myaxios({ url: '/api/Product/GetProductByCode', method: 'get', params: { productCode: productCode } })
      .then(res => {
        if (res.data.code === 200) {
          Object.assign(detail, res.data.data || {})
          console.log('通过productCode获取的详情数据:', res.data.data)
          // 加载图片和附件
          if (detail.productId || detail.ProductId) {
            loadMedia(detail.productId || detail.ProductId)
          }
        } else {
          ElMessage.error(res.data.message || '加载失败')
        }
      })
      .catch(() => ElMessage.error('加载失败'))
  } else {
    ElMessage.error('缺少货品ID或货品编号')
  }
}

// 加载货品图片和附件
const loadMedia = (pid: number) => {
  if (!pid) return
  // API服务器地址（与后端保持一致）
  const apiBaseUrl = 'http://localhost:8080'

  // 加载图片
  myaxios({ url: '/api/Product/GetProductMedia', method: 'get', params: { productId: pid, mediaType: 1 } })
    .then(res => {
      const arr = Array.isArray(res.data.data) ? res.data.data : []
      imageList.value = arr.map((m: any) => ({
        name: m.name || m.url,
        url: m.url.startsWith('http') ? m.url : `${apiBaseUrl}${m.url}`,
        mediaId: m.mediaId
      }))
    })
    .catch(err => console.error('加载图片失败:', err))

  // 加载附件
  myaxios({ url: '/api/Product/GetProductMedia', method: 'get', params: { productId: pid, mediaType: 2 } })
    .then(res => {
      const arr = Array.isArray(res.data.data) ? res.data.data : []
      fileList.value = arr.map((m: any) => ({
        name: m.name || m.url,
        url: m.url.startsWith('http') ? m.url : `${apiBaseUrl}${m.url}`,
        mediaId: m.mediaId
      }))
    })
    .catch(err => console.error('加载附件失败:', err))
}



// 处理删除
const handleDelete = async () => {
  if (!detail.productId) {
    ElMessage.error('货品ID不存在')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除货品 "${detail.productName}" 吗？删除后将无法恢复，同时会删除相关的库存和媒体文件。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const res = await myaxios({
      url: '/api/Product/DeleteProductById',
      method: 'post',
      data: {
        productId: detail.productId
      },
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      // 删除成功后返回货品列表页面
      router.push({ path: '/GetProdut' })
    } else {
      console.error('删除失败，服务器响应:', res.data)
      ElMessage.error(res.data.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除货品失败，详细错误:', error)
      console.error('错误响应:', error.response?.data)
      console.error('错误状态:', error.response?.status)

      let errorMessage = '删除失败，请稍后重试'
      if (error.response?.status === 401) {
        errorMessage = '删除失败：用户未登录或登录已过期'
      } else if (error.response?.status === 403) {
        errorMessage = '删除失败：没有权限执行此操作'
      } else if (error.response?.data?.message) {
        errorMessage = `删除失败：${error.response.data.message}`
      }

      ElMessage.error(errorMessage)
    }
  }
}

// 处理状态切换（启用/停用）
const handleToggleStatus = async () => {
  if (!detail.productId) {
    ElMessage.error('货品ID不存在')
    return
  }

  const currentStatus = detail.productState
  const newStatus = currentStatus === 1 ? 2 : 1
  const actionText = newStatus === 1 ? '启用' : '停用'

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}货品 "${detail.productName}" 吗？`,
      `确认${actionText}`,
      {
        confirmButtonText: `确定${actionText}`,
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await myaxios({
      url: '/api/Product/UpdateProductStatus',
      method: 'post',
      data: {
        productId: detail.productId,
        status: newStatus
      },
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (res.data.code === 200) {
      ElMessage.success(res.data.message || `${actionText}成功`)
      // 更新本地状态
      detail.productState = newStatus
      // 重新加载详情以确保数据同步
      loadDetail()
    } else {
      ElMessage.error(res.data.message || `${actionText}失败`)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('更新货品状态失败:', error)
      ElMessage.error(`${actionText}失败，请稍后重试`)
    }
  }
}

// 打开打印对话框
const openPrintDialog = async () => {
  showPrintDialog.value = true
  // 等待DOM更新后生成二维码
  await nextTick()
  generateQRCode()
}

// 生成二维码
const generateQRCode = async () => {
  const productCode = detail.productCode || detail.ProductCode
  if (!qrCodeCanvas.value || !productCode) return

  try {
    await QRCode.toCanvas(qrCodeCanvas.value, productCode, {
      width: 120,
      margin: 1,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    })
  } catch (error) {
    console.error('生成二维码失败:', error)
  }
}

// 加载入库记录（根据货品ID查询入库明细）
const loadInboundRecords = () => {
  const productId = detail.productId || detail.ProductId
  if (!productId) {
    console.log('loadInboundRecords: productId不存在，跳过加载')
    return
  }

  console.log('loadInboundRecords: 开始加载入库记录，productId=', productId)
  inboundLoading.value = true
  myaxios({
    url: '/api/Warehousing/GetInboundDetailByProductId',
    method: 'get',
    params: {
      productId: productId,
      warehousingCode: inboundFilter.warehousingCode || undefined,
      warehousingTypeId: inboundFilter.warehousingTypeId || undefined,
      warehouseId: inboundFilter.warehouseId || undefined,
      pageindex: inboundPagination.pageIndex,
      pagesize: inboundPagination.pageSize
    }
  })
    .then(res => {
      console.log('loadInboundRecords: 响应数据', res.data)
      if (res.data.code === 200 && res.data.data) {
        inboundRecords.value = res.data.data.data || []
        inboundPagination.total = res.data.data.listCount || 0
      } else {
        inboundRecords.value = []
        inboundPagination.total = 0
      }
    })
    .catch(err => {
      console.error('加载入库记录失败:', err)
      inboundRecords.value = []
      inboundPagination.total = 0
    })
    .finally(() => {
      inboundLoading.value = false
    })
}

// 加载入库类型列表
const loadInboundTypeList = () => {
  myaxios({ url: '/api/Warehousing/GetWarehousingType', method: 'get' })
    .then(res => {
      if (res.data.code === 200) {
        inboundTypeList.value = res.data.data || []
      }
    })
    .catch(err => console.error('加载入库类型失败:', err))
}

// 加载仓库列表
const loadWarehouseList = () => {
  myaxios({ url: '/api/Warehousing/GetWarehouse', method: 'get' })
    .then(res => {
      if (res.data.code === 200) {
        warehouseList.value = res.data.data || []
      }
    })
    .catch(err => console.error('加载仓库列表失败:', err))
}

// 重置入库记录筛选条件
const resetInboundFilter = () => {
  inboundFilter.warehousingCode = ''
  inboundFilter.warehousingTypeId = null
  inboundFilter.warehouseId = null
  inboundPagination.pageIndex = 1
  loadInboundRecords()
}

// 导出入库记录
const exportInboundRecords = () => {
  const productId = detail.productId || detail.ProductId
  if (!productId) return

  const params = new URLSearchParams({
    productId: productId.toString(),
    pageindex: '1',
    pagesize: '10000'
  })
  if (inboundFilter.warehousingCode) params.append('warehousingCode', inboundFilter.warehousingCode)
  if (inboundFilter.warehouseId) params.append('warehouseId', inboundFilter.warehouseId.toString())

  window.open(`http://localhost:8080/api/Warehousing/ImproerExcelWarehouseing?${params.toString()}`)
}

// 跳转入库详情
const goInboundDetail = (row: any) => {
  router.push({
    path: '/Warehousing/DetailWarehousingView',
    query: { warehousingId: row.warehousingId }
  })
}

// 处理打印
const handlePrint = () => {
  // 生成打印内容
  const printContent = document.getElementById('printContent')
  if (!printContent) {
    ElMessage.error('打印内容不存在')
    return
  }

  // 创建新窗口进行打印
  const printWindow = window.open('', '_blank', 'width=800,height=600')
  if (!printWindow) {
    ElMessage.error('无法打开打印窗口')
    return
  }

  // 设置打印页面的HTML内容
  printWindow.document.write(`
    <!DOCTYPE html>
    <html>
    <head>
      <title>打印货品信息</title>
      <style>
        body {
          margin: 20px;
          font-family: Arial, sans-serif;
          font-size: 14px;
        }
        .print-header {
          display: flex;
          align-items: flex-start;
          gap: 20px;
          padding: 20px;
          border: 1px solid #ddd;
        }
        .qr-code-section {
          text-align: center;
          min-width: 140px;
        }
        .product-code {
          margin-top: 8px;
          font-weight: bold;
          font-size: 16px;
        }
        .product-info-table {
          flex: 1;
        }
        .info-table {
          width: 100%;
          border-collapse: collapse;
        }
        .info-table td {
          padding: 12px;
          border: 1px solid #ddd;
          vertical-align: middle;
        }
        .info-table .label {
          background-color: #f5f5f5;
          font-weight: bold;
          width: 120px;
        }
        .info-table .value {
          background-color: white;
        }
        @media print {
          body { margin: 0; }
          .print-header { border: 2px solid #000; }
        }
      </style>
    </head>
    <body>
      ${printContent.outerHTML}
    </body>
    </html>
  `)

  printWindow.document.close()

  // 等待内容加载完成后打印
  printWindow.onload = () => {
    printWindow.print()
    printWindow.close()
  }

  showPrintDialog.value = false
  ElMessage.success('打印任务已发送')
}

// 监听标签页切换，按需加载入库记录
watch(activeTab, (newTab) => {
  if (newTab === 'inbound') {
    // 每次切换到入库记录标签页都重新加载（确保productId已加载）
    const productId = detail.productId || detail.ProductId
    if (productId) {
      loadInboundRecords()
    }
  }
})

onMounted(() => {
  loadDetail()
  // 预加载入库类型和仓库列表
  loadInboundTypeList()
  loadWarehouseList()
})
</script>

<style scoped>
/* 轮播图样式 */
:deep(.el-carousel__item) {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

/* 描述列表标签宽度 */
:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: 600;
}

/* 描述列表内容样式 */
:deep(.el-descriptions__content) {
  color: #606266;
}

/* 标签页样式 */
:deep(.el-tabs__item) {
  font-weight: 500;
}

/* 空状态样式 */
:deep(.el-empty__description) {
  color: #909399;
}

/* 打印内容样式 */
.print-content {
  padding: 20px;
}

.print-header {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.qr-code-section {
  text-align: center;
  min-width: 140px;
}

.product-code {
  margin-top: 8px;
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.product-info-table {
  flex: 1;
}

.info-table {
  width: 100%;
  border-collapse: collapse;
}

.info-table td {
  padding: 12px;
  border: 1px solid #ddd;
  vertical-align: middle;
}

.info-table .label {
  background-color: #f5f5f5;
  font-weight: bold;
  width: 120px;
  color: #303133;
}

.info-table .value {
  background-color: white;
  color: #606266;
}
</style>
